package com.study.talk.app.home.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;

import androidx.annotation.NonNull;
import androidx.viewpager2.widget.ViewPager2;

import com.google.android.material.tabs.TabLayout;
import com.study.talk.app.base.EventBusBaseFragment;
import com.study.talk.R;
import com.study.talk.adapter.ChatCacheListViewAdapter;
import com.study.talk.app.base.BaseActivity;
import com.study.talk.app.chat.ChatActivity;
import com.study.talk.app.chat.GroupChatActivity;
import com.study.talk.databinding.FragmentHomeBinding;
import com.study.talk.entity.ChatCache;
import com.study.talk.entity.GroupInfo;
import com.study.talk.entity.GroupMessageRecord;
import com.study.talk.entity.MessageRecord;
import com.study.talk.entity.UserInfo;
import com.study.talk.entity.bus.UpdateHomeFragmentChatList;
import com.study.talk.util.DateUtil;
import com.study.talk.util.GsonInstance;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class HomeFragment extends EventBusBaseFragment {



    private BaseActivity activity;
    private FragmentHomeBinding fragmentHomeBinding;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        activity = (BaseActivity) getActivity();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        fragmentHomeBinding = FragmentHomeBinding.inflate(inflater,container,false);
        initData();
        return fragmentHomeBinding.getRoot();
    }


    private void initData(){
        List<UserInfo> friendList = activity.getApp().friendList;
        List<GroupInfo> groupList = activity.getApp().groupList;
        List<ChatCache> dataList = new ArrayList<>();
        for (UserInfo userInfo : friendList) {
            ChatCache cache = new ChatCache();
            List<MessageRecord> messageRecordList = activity.getApp().db.messageDao().getListByChatId(userInfo.getId());
            if (messageRecordList != null && !messageRecordList.isEmpty()){
                MessageRecord messageRecord = messageRecordList.get(messageRecordList.size() - 1);
                cache.setCreateTime(messageRecord.getDateTime());
                cache.setAvatar(messageRecord.getAvatar());
                cache.setRead(messageRecord.getRead());
                cache.setLastContent(messageRecord.getMessageType() == 0 ? messageRecord.getContent() : "[图片]");
            }else {
                cache.setCreateTime(userInfo.getCreateTime());
                cache.setAvatar(userInfo.getAvatar());
                cache.setRead(true);
                cache.setLastContent(userInfo.getIntroduce());
            }
            cache.setName(userInfo.getUsername());
            cache.setGroupInfo(null);
            cache.setUserInfo(userInfo);
            cache.setChatType(1);
            dataList.add(cache);
        }
        for (GroupInfo groupInfo : groupList) {
            List<GroupMessageRecord> messageRecordList = activity.getApp().db.groupMessageDao().getListByGroupId(groupInfo.getId());
            ChatCache cache = getChatCache(groupInfo, messageRecordList);
            dataList.add(cache);
        }
        dataList.sort((a, b) -> {
            try {
                return Objects.requireNonNull(DateUtil.format.parse(b.getCreateTime().replaceAll("T", " "))).compareTo(DateUtil.format.parse(a.getCreateTime().replaceAll("T", " ")));
            } catch (ParseException e) {
                throw new RuntimeException(e);
            }
        });
        ChatCacheListViewAdapter adapter = new ChatCacheListViewAdapter(dataList);
        fragmentHomeBinding.homeListView.setAdapter(adapter);
        fragmentHomeBinding.homeListView.setEmptyView(fragmentHomeBinding.fragmentFriendEmptyView);
        fragmentHomeBinding.homeListView.setOnItemClickListener((parent, view, position, id) -> {
            if (dataList.get(position).getChatType() == 1){
                UserInfo userInfo = dataList.get(position).getUserInfo();
                Intent intent = new Intent(activity.getApplicationContext(), ChatActivity.class);
                intent.putExtra("data", GsonInstance.instance.toJson(userInfo));
                activity.startActivity(intent);
            }else {
                GroupInfo groupInfo = dataList.get(position).getGroupInfo();
                Intent intent = new Intent(activity.getApplicationContext(), GroupChatActivity.class);
                intent.putExtra("data", GsonInstance.instance.toJson(groupInfo));
                activity.startActivity(intent);
            }
        });
    }

    private @NonNull ChatCache getChatCache(GroupInfo groupInfo, List<GroupMessageRecord> messageRecordList) {
        ChatCache cache = new ChatCache();
        if (messageRecordList != null && !messageRecordList.isEmpty()){
            GroupMessageRecord messageRecord = messageRecordList.get(messageRecordList.size() - 1);
            cache.setCreateTime(messageRecord.getDateTime());
            cache.setAvatar(groupInfo.getAvatar());
            cache.setRead(messageRecord.getRead());
            cache.setLastContent(messageRecord.getMessageType() == 0 ? messageRecord.getContent() : "[图片]");
        }else {
            cache.setCreateTime(groupInfo.getCreateTime());
            cache.setAvatar(groupInfo.getAvatar());
            cache.setRead(true);
            cache.setLastContent(groupInfo.getIntroduce());
        }
        cache.setName(groupInfo.getName());
        cache.setGroupInfo(groupInfo);
        cache.setUserInfo(null);
        cache.setChatType(2);
        return cache;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void updateChatList(UpdateHomeFragmentChatList updateHomeFragmentChatList){
        initData();
    }

    @Override
    public void onResume() {
        super.onResume();
        initData();
    }
}